import requests
import re
import json
import random

from core import Bot


class BPush(object):

    def __init__(self):
        try:
            with open('bpush.json') as f:
                self.bpush = json.load(f)
            self.bpush_new = self.bpush['new']
            self.bpush_already = self.bpush['already']

            if 'notRequest' not in self.bpush:
                self.bpush['notRequest'] = []
            self.bpush_notRequest = self.bpush['notRequest']
        except FileNotFoundError as e:
            self.bpush_new = []
            self.bpush_already = []
            self.bpush_notRequest = []

        self.file_close = open("bpush.json", 'w')

    def __del__(self):
        json.dump({
            "new": self.bpush_new,
            "already": self.bpush_already,
            "notRequest": self.bpush_notRequest
        }, self.file_close, indent=4)
        self.file_close.close()

    def already_filter(self, data: list):
        """
        过滤已经发送过的
        :param data:
        :return:
        """
        results = []
        bvids = [x['bvid'] for x in self.bpush_already]

        for item in data:
            if item['bvid'] in bvids:
                continue
            results.append(item)
        return results

    def new_filter(self, data: list):
        """
        过滤已经保存过的
        :param data:
        :return:
        """
        results = []
        bvids = [x['bvid'] for x in self.bpush_new]

        for item in data:
            if item['bvid'] in bvids or item['stat']['view'] < 50000:
                continue

            results.append(item)
        return results

    def get_one(self):
        """
        从 new 中抽取一个出来进行发送
        发送之后删除 new 中的元素
        添加元素到 already 中
        :return:
        """
        if len(self.bpush_new) == 0:
            return False

        item = self.bpush_new[random.randint(0, len(self.bpush_new) - 1)]
        self.bpush_already.append(item)
        self.bpush_new.remove(item)
        return item

    def bilibili_show(self):
        return len(self.bpush_new), len(self.bpush_already)

    def get_not_request(self):
        item = self.bpush_already[random.randint(0, len(self.bpush_already))]
        if item['bvid'] not in self.bpush_notRequest:
            self.bpush_notRequest.append(item['bvid'])
            return item
        return self.get_not_request()

    def bilibili_from_bvid(self, bvid):
        r = requests.get(
            # "https://www.bilibili.com/v/channel/159571?tab=featured&spm_id_from=333.788.b_765f746167.2",
            "https://www.bilibili.com/video/" + bvid
        )

        m = re.search(r'</script><script>window.__INITIAL_STATE__=(\{.*?\});\(function\(\)\{var s;', r.text, re.S)

        data = json.loads(m.group(1))

        related = data['related']
        related = self.new_filter(self.already_filter(related))

        """
        爬行到的数据保存到 new 中，下次发送
        """
        for item in related:
            self.bpush_new.append(item)

    def bilibili(self):
        try:
            bvid = self.get_not_request()['bvid']
        except RecursionError as e:
            bvid = "BV1Yf4y1D74r"

        r = requests.get(
            # "https://www.bilibili.com/v/channel/159571?tab=featured&spm_id_from=333.788.b_765f746167.2",
            "https://www.bilibili.com/video/" + bvid
        )

        m = re.search(r'</script><script>window.__INITIAL_STATE__=(\{.*?\});\(function\(\)\{var s;', r.text, re.S)

        data = json.loads(m.group(1))

        related = data['related']
        related = self.new_filter(self.already_filter(related))

        """
        爬行到的数据保存到 new 中，下次发送
        """
        for item in related:
            self.bpush_new.append(item)

        # print(len(related))
        #
        # for item in related:
        #     print(item)

        # item = related[random.randint(0, len(related)-1)]
        # title = item['title']
        # pic = item['pic']
        # bvid = item['bvid']
        # return bvid, title, pic


if __name__ == '__main__':
    # b = BPush()
    # print(b.get_one())
    # b.bilibili()
    # print(b.bilibili_show())

    bot = Bot(auth_key="12345678", qq=1398231927)
    bilibili = BPush()
    item = bilibili.get_one()
    title = item['title']
    pic = item['pic']
    bvid = item['bvid']

    group_id = "915172971"
    bot.sendGroupMessage(
        target=group_id,
        text=[
            {
                "type": "Xml",
                "xml": """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <msg serviceID="1" brief="定时推送"
    action="web" url="https://www.bilibili.com/video/{}">
    <item>
    <title>{}</title>
    <picture cover="{}"/>
    </item>
    </msg>""".format(bvid, title, pic)
            }
        ]
    )
